package top.wshape1.shiziapi.project.handler;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.wshape1.shiziapi.common.constant.AuthConstant;
import top.wshape1.shiziapi.common.domain.CommonUser;
import top.wshape1.shiziapi.common.utils.Base64Util;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-12-10
 */

@Component
public class LoginContextHandler implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userBase64 = request.getHeader(AuthConstant.HEADER_PAYLOAD_NAME);

        if (userBase64 == null)
            return true;

        CommonUser commonUser = Base64Util.decodeAndParse(userBase64, CommonUser.class);
        THREAD_LOCAL.set(commonUser);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        THREAD_LOCAL.remove();
    }

    /*
     * ==============
     */

    private static final ThreadLocal<CommonUser> THREAD_LOCAL = new ThreadLocal<>();

    public static CommonUser getUser() {
        return THREAD_LOCAL.get();
    }

    public static long getUserId() {
        CommonUser user = getUser();
        if (user == null)
            return -1;
        return user.getId();
    }

}
